/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Planilla_View_Add.java
 *
 * Created on 2/05/2012, 11:44:10 PM
 */
package v;

import c.MedicamentoController;
import c.PlanillasController;
import core.constructor.constructor;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringEscapeUtils;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import tools.DatosComboBox;
import tools.Util;

/**
 *
 * @author Usuario
 */
//validar que un medico no tenga asignado planillas el mismo dia en el mismo 
//horario
//
public class Medicamentos_View_Add extends javax.swing.JPanel {

    private constructor c;
    private DatosComboBox cbx;
    private String id_medico;
    private MedicamentoController controlador = new MedicamentoController();
    private String mod = "";
    private String llavePrimaria = "";
    private String campoPK;
    private String noIdentificacion = "";

    public Medicamentos_View_Add(Object... e) {
        initComponents();
        controlador = new MedicamentoController();
        config(e);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        Panel = new javax.swing.JPanel();
        bAgregar = new javax.swing.JButton();
        bCancelar = new javax.swing.JButton();
        jXTitledSeparator1 = new org.jdesktop.swingx.JXTitledSeparator();
        jLabel4 = new javax.swing.JLabel();
        cNombre = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        cbPresentacion = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taComponentes = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        taObservaciones = new javax.swing.JTextArea();

        setLayout(new java.awt.GridBagLayout());

        Panel.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                PanelInputMethodTextChanged(evt);
            }
        });

        bAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/guardar32.png"))); // NOI18N
        bAgregar.setText("Guardar");
        bAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAgregarActionPerformed(evt);
            }
        });

        bCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/cancelar32.png"))); // NOI18N
        bCancelar.setText("Cancelar");
        bCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelarActionPerformed(evt);
            }
        });

        jXTitledSeparator1.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
        jXTitledSeparator1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
        jXTitledSeparator1.setTitle("Datos Medicamento");

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Nombre");

        cNombre.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cNombreActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel7.setText("Presentación");

        cbPresentacion.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("Componentes");

        taComponentes.setColumns(20);
        taComponentes.setLineWrap(true);
        taComponentes.setRows(3);
        jScrollPane1.setViewportView(taComponentes);

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel6.setText("Observaciones");

        taObservaciones.setColumns(20);
        taObservaciones.setLineWrap(true);
        taObservaciones.setRows(3);
        jScrollPane2.setViewportView(taObservaciones);

        javax.swing.GroupLayout PanelLayout = new javax.swing.GroupLayout(Panel);
        Panel.setLayout(PanelLayout);
        PanelLayout.setHorizontalGroup(
            PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelLayout.createSequentialGroup()
                .addGroup(PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PanelLayout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelLayout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(PanelLayout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(bAgregar)
                        .addGap(10, 10, 10)
                        .addComponent(bCancelar))
                    .addGroup(PanelLayout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addGroup(PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(PanelLayout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(45, 45, 45)
                                .addComponent(cNombre))
                            .addGroup(PanelLayout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(7, 7, 7)
                                .addComponent(jScrollPane1))
                            .addGroup(PanelLayout.createSequentialGroup()
                                .addComponent(jLabel7)
                                .addGap(16, 16, 16)
                                .addComponent(cbPresentacion, javax.swing.GroupLayout.PREFERRED_SIZE, 335, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                .addContainerGap())
        );
        PanelLayout.setVerticalGroup(
            PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(PanelLayout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addComponent(jXTitledSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addGroup(PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PanelLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel4))
                    .addComponent(cNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(PanelLayout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jLabel7))
                    .addComponent(cbPresentacion, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addGroup(PanelLayout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(11, 11, 11)
                .addGroup(PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addGroup(PanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bAgregar)
                    .addComponent(bCancelar)))
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 11, 11);
        add(Panel, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void bAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAgregarActionPerformed
        prepararTransaccion();
    }//GEN-LAST:event_bAgregarActionPerformed

    private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
        if (c != null) {
            c.ventPrincipal();
        } else {
            Logger.getLogger(Acudiente_View_Add.class.getName()).log(Level.WARNING, "La Clase Constructor no ha sido instanciada");
        }

    }//GEN-LAST:event_bCancelarActionPerformed

    private void cNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cNombreActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cNombreActionPerformed

    private void PanelInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_PanelInputMethodTextChanged
    }//GEN-LAST:event_PanelInputMethodTextChanged
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel Panel;
    private javax.swing.JButton bAgregar;
    private javax.swing.JButton bCancelar;
    private javax.swing.JTextField cNombre;
    private javax.swing.JComboBox cbPresentacion;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator1;
    private javax.swing.JTextArea taComponentes;
    private javax.swing.JTextArea taObservaciones;
    // End of variables declaration//GEN-END:variables

    private void config(Object... e) {

        if (e.length > 0) {
            try {

                cbx = new DatosComboBox();
                cbPresentacion.setModel(new javax.swing.DefaultComboBoxModel(cbx.cbPresentacionMedicamento()));
                AutoCompleteDecorator.decorate(cbPresentacion);

                c = (constructor) e[0];

                //Configura la Interfaz para el Modo en el que fue invocado
                configModo((String) e[1], (String) e[2]);
            } catch (Exception exc) {
                System.err.println("(config())Error de Asignacion , compruebe el numero de Parametros que envia .. " + exc.getMessage());
                exc.printStackTrace();
            }
        }
        // Indicar a las 'migas de pan' donde estamos.
        c.setNavegar("Medicamentos_View_Grid");
        c.setLabelModulo("Medicamentos");
        c.setLabelAccion("Ingresar Medicamento");
    }

    private void prepararTransaccion() {
        //Herramientas
        tools.Util u = new tools.Util();
        String tablaBD = "medicamento";

        StringBuilder sqlAndRestricciones = new StringBuilder();
        StringBuilder camposBD = new StringBuilder();
        StringBuilder valoresBD = new StringBuilder();

        sqlAndRestricciones.append("Nombre Medicamento@nombre='").append(cNombre.getText().toLowerCase()).append("'[req-(0,40)]UNQ").append(noIdentificacion).append("]&");
        sqlAndRestricciones.append("Presentación Medicamento@id_presentacion=").append(cbx.getKeyPresenMedicamento(cbPresentacion)).append("[req-num(0,0)]&");
        sqlAndRestricciones.append("Componentes Medicamento@componentes='").append(StringEscapeUtils.escapeEcmaScript(taComponentes.getText().toLowerCase())).append("'[req-(0,50)]&");
        sqlAndRestricciones.append("Observaciones sobre su Uso@observaciones='").append(StringEscapeUtils.escapeEcmaScript(taObservaciones.getText().toLowerCase())).append("'[-(0,100)]");


        String mensajeUsuario = controlador.prepararTransaccion(tablaBD, sqlAndRestricciones, mod, "El Medicamento", campoPK);

        c.informarUsuario(mensajeUsuario);

        //Asignar el Nuevo valor al Campo Identificacion (Unique Campos)
        noIdentificacion = cNombre.getText().toLowerCase();
        
        if (mensajeUsuario.contains("ok[")){
            Util.limpiarCamposForm(this);
        }
    }

    private void configModo(String m, String key) {
        mod = m;

        String SQL_BUSCAR = String.format("SELECT med.id_medicamento ,med.nombre , pres.descripcion , med.componentes , med.observaciones FROM medicamento med , presentacion_medicamento pres WHERE med.id_presentacion = pres.id_presentacion AND med.id_medicamento  = %s", key);

        if (!m.equals("")) {

            if ("INSERT".equals(mod)) {
                c.setLabelAccion("Agregar Medicamentos al Sistema");
            }

            if (!m.equals("INSERT")) {
                setLlavePrimaria(key);
                campoPK = "id_medicamento = " + key;
            }

            if (m.equals("SELECT")) {
                System.out.println("mod = " + m);
                System.out.println("key = " + key);
                estadoComponentes(false);
                c.setLabelAccion("Consultar Medicamento");
                setMedicamento(controlador.buscar(SQL_BUSCAR));
            } else if (m.equals("UPDATE")) {
                llavePrimaria = key;
                System.out.println("mod = " + m);
                System.out.println("key = " + key);
                estadoComponentes(true);
                c.setLabelAccion("Modificar Medicamento");
                setMedicamento(controlador.buscar(SQL_BUSCAR));
                bAgregar.setText("Actualizar");
                bAgregar.setEnabled(true);
                //Cambiar icono here...

                //Tomar cuando arranque la pantalla los campos UNQ
                noIdentificacion = cNombre.getText().toLowerCase();
                System.out.println("noIdentificacion = " + noIdentificacion);
            }
        }
    }

    public String getLlavePrimaria() {
        return llavePrimaria;
    }

    public void setLlavePrimaria(String llavePrimaria) {
        this.llavePrimaria = llavePrimaria;
    }

    private void estadoComponentes(boolean b) {
        cNombre.setEditable(b);
        cbPresentacion.setEditable(b);
        taComponentes.setEditable(b);
        taObservaciones.setEnabled(b);
    }

    private void setMedicamento(Object[][] buscar) {
        //Herramientas
        tools.Util u = new tools.Util();

        cNombre.setText(buscar[0][1].toString());
        cbPresentacion.setSelectedItem(buscar[0][2].toString());
        taComponentes.setText(buscar[0][3].toString());
        taObservaciones.setText(buscar[0][4].toString());
    }
}